{
  Nassy - anti-spam for IM clients
  Copyright (C) 2008-2009 Denis Shemanayev aka nis
                          mailto: nis@nis.org.ua
                          mailto: Denis.Shemanayev@gmail.com

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
}
{ $Id: uLog.pas 5 2009-06-19 12:15:33Z Denis.Shemanayev $ }

unit uLog;

interface

procedure LogInit(const FileName: WideString);
function LogInited: Boolean;
procedure LogClose;
procedure LogAdd(const Sender, Text: WideString; Time: Integer; Probability: Extended);

implementation

uses
  SyncObjs, Windows, SysUtils, DateUtils, uConst, WideSysUtils;

var
  CS: TCriticalSection;
  Fl: THandle;
  HasRecords: Boolean = False;
  LogFileName: WideString = '';

{***********************************************************}
function LogInited: Boolean;
begin
  Result := Fl <> 0;
end;

{***********************************************************}
procedure LogInit(const FileName: WideString);
begin
  LogClose;
  CS := TCriticalSection.Create;
  LogFileName := FileName;
  Fl := CreateFileW(PWideChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0);
end;

{***********************************************************}
procedure LogClose;
begin
  if Fl <> 0 then
    CloseHandle(Fl);
  Fl := 0;
  if Assigned(CS) then
    FreeAndNil(CS);
  if (not HasRecords) and (WideFileExists(LogFileName)) then
    WideDeleteFile(LogFileName);
end;

{***********************************************************}
procedure LogAdd(const Sender, Text: WideString; Time: Integer; Probability: Extended);
var
  s: WideString;
  d: Cardinal;
begin
  CS.Enter;
  HasRecords := True;
  s := Sender + WideString(' (') + WideString(FormatDateTime(C_LOG_DATE_FMT,
   UnixToDateTime(Time))) + WideString(') [') + FloatToStr(Probability) + WideString(']') +
   WideChar(#13) + WideChar(#10) + Text + WideChar(#13) + WideChar(#10);
  try
    WriteFile(Fl, PWideChar(s)^, Length(s) * SizeOf(WideChar), d, nil);
  finally
    FlushFileBuffers(Fl);
    CS.Leave;
  end;
end;

initialization

finalization
  LogClose;

end.
